//
//  MoreViewController.m
//  HimalayaMusic
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 WXCLegendary. All rights reserved.
//

#import "MoreViewController.h"

@interface MoreViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong)NSMutableArray *topItemArray;
@property (nonatomic, strong)NSMutableArray *topScrollArray;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataSource;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)UIView *drawView;
@property (nonatomic, assign)BOOL ifColseDrawer;
@end

@implementation MoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    [self getTopViewNetData];
    [self createCollectionView];
}

- (void)getTopViewNetData {

    NSString *more = @"更多";
    more = [more stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/category/tagsWithoutCover?categoryId=%@&contentType=album&device=android&title=%@", self.categoryId, more];
    
    [WXCNetWorkTool getWithUrl:string parameter:nil httpHeader:nil responseType:ResponseTypeJson success:^(id result) {
        self.topItemArray = [NSMutableArray array];
        for (NSDictionary *dic in result[@"list"]) {
             TopCollectionViewModel *topModel = [[TopCollectionViewModel alloc] initWithDictionary:dic];
            [self.topItemArray addObject:topModel];
        }
        [self createScrollViewWithArray:self.topItemArray];
        [self createButton];
        [self createDrawerWithArray:self.topItemArray];
        //顶部scrollview请求完成后进行下一步数据请求
        [self.collectionView reloadData];
        
        
    } fail:^(NSError *error) {
        
        
    }];
    
}

- (void)createCollectionView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.itemSize = CGSizeMake(self.view.width, self.view.height - 40 - 64 - 49);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 104, self.view.width, self.view.height - 40 - 64 - 49) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    [self.collectionView registerClass:[DownCollectionViewCell class] forCellWithReuseIdentifier:@"DownCollectionViewCellIdentifier"];
    [self.view addSubview:self.collectionView];


    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.topItemArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *tname = [[self.topItemArray[indexPath.item] tname] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/category/album?calcDimension=hot&categoryId=%@&device=android&pageId=1&pageSize=20&status=0&tagName=%@", self.categoryId, tname];
    DownCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DownCollectionViewCellIdentifier" forIndexPath:indexPath];

    cell.url = string;
    
    //利用block跳转
    
    cell.block = ^(NSString *string) {
        AlbumViewController *albumVC = [[AlbumViewController alloc] init];
        albumVC.hotRecommendListModel = [[HotRecommendListModel alloc] init];
        albumVC.hotRecommendListModel.albumId = string;
        [self.navigationController pushViewController:albumVC animated:YES];
    };
    
    return cell;
}

- (void)createScrollViewWithArray:(NSMutableArray *)array {
    self.topScrollArray = [NSMutableArray array];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.width - 40, 40)];
    [self.view addSubview:self.scrollView];
self.scrollView.backgroundColor = [UIColor colorWithRed:206 / 255.0 green:71 / 255.0 blue:56 / 255.0 alpha:1];
  
    for (int i = 0; i < array.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        
        button.tag = 100 + i;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        //button 宽度自适应
        NSDictionary *TagLabeldic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        CGRect tagRect = [[array[i] tname] boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:TagLabeldic context:nil];
        UIButton *lastButton = self.topScrollArray.lastObject;
        
        if (i == 0) {
            button.frame = CGRectMake(10, 0, tagRect.size.width, 40);
            [self.topScrollArray addObject:button];
        } else {
            button.frame = CGRectMake(10 + lastButton.right, 0, tagRect.size.width, 40);
            [self.topScrollArray addObject:button];
        }
        [self.scrollView addSubview:button];
        self.scrollView.scrollEnabled = YES;
        self.scrollView.contentSize = CGSizeMake(lastButton.right + 10, 40);
        self.scrollView.showsHorizontalScrollIndicator = NO;
        [button setTitle:[array[i] tname] forState:UIControlStateNormal];
        self.scrollView.bounces= NO;
    }
}

- (void)buttonAction:(UIButton *)sender {
    for (int i = 0; i < self.topItemArray.count; i++) {
        if ([[self.topItemArray[i] tname] isEqualToString:sender.titleLabel.text]) {
             UIButton *button = (UIButton *)self.topScrollArray[i];
            
            
            
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            
            
            [self.collectionView setContentOffset:CGPointMake(i * self.view.width, 0) animated:NO];
           
            if (button.left - self.scrollView.contentOffset.x > (self.view.width - 40) / 2) {
                //判断到最后，不需要偏移
                float miner = button.left - self.scrollView.contentOffset.x;
                float other = miner - (self.view.width - 40) / 2;
                if (other + self.scrollView.contentOffset.x > self.scrollView.contentSize.width - self.scrollView.width) {
                    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentSize.width - self.scrollView.width, 0) animated:YES];
                } else {
                    [self.scrollView setContentOffset:CGPointMake(other + self.scrollView.contentOffset.x, 0) animated:YES];
                }
            } else {
                if (self.scrollView.contentOffset.x != 0) {
                    float miner = button.left - self.scrollView.contentOffset.x;
                    float other = miner - (self.view.width - 40) / 2;
                    if (other + self.scrollView.contentOffset.x < 0) {
                        self.scrollView.contentOffset = CGPointMake(0, 0);
                    } else {
                        [self.scrollView setContentOffset:CGPointMake(other + self.scrollView.contentOffset.x, 0) animated:YES];
                    }
                }
            }
        }
        else {
            //其他按钮颜色字体大小不变
            UIButton *button = (UIButton *)self.topScrollArray[i];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
        }
    }
}

- (void)createButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setBackgroundImage:[UIImage imageNamed:@"zhankai"] forState:UIControlStateNormal];
    
    button.backgroundColor = [UIColor colorWithRed:206 / 255.0 green:71 / 255.0 blue:56 / 255.0 alpha:1];
    button.frame = CGRectMake(self.scrollView.right, 64, 40, 40);
    [button addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [button setTitle:@"展开" forState:UIControlStateNormal];

    [self.view addSubview:button];
    
    
}

//抽屉调用的方法

- (void)rightButtonAction:(UIButton *)button {
    [self.view bringSubviewToFront:self.drawView];
    
    if (!self.ifColseDrawer) {
         self.drawView.frame = CGRectMake(0, 40 + 64, self.view.width, self.view.height - 64 - 40 - 49);
//        [button setTitle:@"关闭" forState:UIControlStateNormal];
        self.ifColseDrawer = !self.ifColseDrawer;
    } else {
        self.drawView.frame = CGRectMake(0, -(self.view.height - 64 - 40 - 49), self.view.width, self.view.height - 64 - 40 - 49);
//        [button setTitle:@"展开" forState:UIControlStateNormal];
        self.ifColseDrawer = !self.ifColseDrawer;

    }
    
}

- (void)createDrawerWithArray:(NSArray *)array {

    self.drawView = [[UIView alloc] initWithFrame:CGRectMake(0, -(self.view.height - 64 - 40 - 49), self.view.width, self.view.height - 64 - 40 - 49)];
    self.drawView.backgroundColor = [UIColor grayColor];

    [self.view addSubview:self.drawView];

    int k = 0;
    //写两层for循环,创建抽屉button
    for (int i = 0; i < array.count / 3; i++) {
        for (int j = 0; j < 3; j++) {
           UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            button.frame = CGRectMake((10 +(self.view.width - 40) / 3) * j + 10, i * 50, (self.view.width - 40) / 3, 40);
            button.backgroundColor = [UIColor whiteColor];
            [button setTitle:[array[k] tname] forState:UIControlStateNormal];
            [self.drawView addSubview:button];
            k++;
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        
    }
    
    
    
    
    
    
    
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
